package com.jxzn.locust.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxzn.locust.config.AuthScanRegister;
import com.jxzn.locust.dao.AbstractRepository;
import com.jxzn.locust.dao.ResourceRepository;
import com.jxzn.locust.dto.ModuleAuthDTO;
import com.jxzn.locust.model.SysResource;
import com.jxzn.locust.service.SysResourceService;
import com.jxzn.locust.support.Auth;
import com.jxzn.locust.support.Module;

@Service
@Transactional
public class SysResourceServiceImpl implements SysResourceService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ResourceRepository resourceRepository;

    @Override
    public AbstractRepository<SysResource> getRepository() {
        return resourceRepository;
    }

    @Override
    public void init() {
        Map<Module, ModuleAuthDTO> moduleMap = AuthScanRegister.moduleMap;
        logger.info("初始化系统权限资源...");
        List<SysResource> resourceList = resourceRepository.findAll();
        Set<String> keySet = new HashSet<>();
        for (SysResource res : resourceList) {
            keySet.add(res.getUuid());
        }

        Set<String> existedSet = new HashSet<>();

        List<SysResource> newResourceList = new ArrayList<>();
        for (Map.Entry<Module, ModuleAuthDTO> entry : moduleMap.entrySet()) {
            Module module = entry.getKey();
            ModuleAuthDTO dto = entry.getValue();
            for (Auth auth : dto.getAuthSet()) {
                SysResource res = new SysResource(module, auth);
                if (keySet.contains(res.getUuid())) {
                    existedSet.add(res.getUuid());
                    continue;
                }
                res.setDeleted(Boolean.FALSE);
                newResourceList.add(res);
            }
        }
        if (!newResourceList.isEmpty()) {
            logger.info("初始化系统权限资源，保存资源数={}", newResourceList.size());
            resourceRepository.saveAll(newResourceList);
        }
        if (!existedSet.isEmpty()) {
            resourceRepository.updateByUuid(existedSet);
        }
        logger.info("初始化系统权限资源完成.");
    }

    @Override
    public List<SysResource> findByRoleId(int roleId) {
        return resourceRepository.findByRoleId(roleId);
    }

}
